package com.android.picotts.ui.activity.pick;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.picotts.R;
import com.android.picotts.ui.activity.common.AlpaIndexListAdapter;
import com.android.picotts.ui.activity.common.AlpaIndexListAdapter.PYRender;
import com.android.picotts.ui.activity.pick.FileListAdapter.PFile;
import com.android.picotts.util.PinyinUtil;

public class FileListAdapter extends AlpaIndexListAdapter<PFile> implements OnClickListener {
    private Context mcontext = null;
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    private int chkPosition = -1;
    
    public FileListAdapter(Context context) {
        super(context);
        mcontext = context;
    }
    
    public File getCheckFile() {
        return chkPosition >= 0 ? getItem(chkPosition).file : null; 
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ListHolder mListHolder = null;

        if (convertView == null) {
            convertView = LayoutInflater.from(mcontext).inflate(R.layout.listitem_pick, null);
            mListHolder = new ListHolder();
            mListHolder.mfileIcon = (ImageView) convertView.findViewById(R.id.icon);
            mListHolder.mfileName = (TextView) convertView.findViewById(R.id.name);
            mListHolder.mfileSize = (TextView) convertView.findViewById(R.id.size);
            mListHolder.mfileTime = (TextView) convertView.findViewById(R.id.title);
            mListHolder.mChkBox =  (CheckBox) convertView.findViewById(R.id.checkbox);
            
            mListHolder.mChkBox.setOnClickListener(this);
            
            convertView.setTag(mListHolder);
        } else {
            mListHolder = (ListHolder) convertView.getTag();
        }
        
        File f = this.getItem(position).file;
        if (f != null) {
            int icon = this.getFileIcon(f);
            if (icon == -1) {
                Drawable drawable = this.getApkIcon(f.getAbsolutePath());
                if (drawable != null) {
                    mListHolder.mfileIcon.setImageDrawable(drawable);
                } else {
                    mListHolder.mfileIcon.setImageResource(R.drawable.icon_file);
                }
            } else {
                mListHolder.mfileIcon.setImageResource(icon);
            }
            mListHolder.mfileName.setText(f.getName());
            if (f.isFile()) {
                mListHolder.mfileSize.setText(this.getFileSize(f.length()));
            } else {
                mListHolder.mfileSize.setText("");

            }
            mListHolder.mfileTime.setText(this.getFileTime(f.lastModified()));
        }
        
        mListHolder.mChkBox.setChecked(chkPosition == position);
        mListHolder.mChkBox.setTag(position);
        return convertView;
    }
    
    
    @Override
    public void onClick(View v) {
        int pos = (Integer)v.getTag();
        if(pos == chkPosition) {
            chkPosition = -1;
        }else {
            chkPosition = pos;
        }
        notifyDataSetChanged();
    }

    public int getFileIcon(File f) {
        int icon = 0;

        String str = FileMimeTypes.getFileIcon(f);
        if (str == null) {
            icon = -1;
        } else {
            Resources res = mcontext.getResources();
            icon = res.getIdentifier(str, "drawable", mcontext.getPackageName());

            if (icon <= 0)
                icon = R.drawable.icon_file;
        }

        return icon;
    }

    public Drawable getApkIcon(String path) {
        PackageManager pm = mcontext.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;

            if (Build.VERSION.SDK_INT >= 8) {
                appInfo.sourceDir = path;
                appInfo.publicSourceDir = path;
            }

            return appInfo.loadIcon(pm);
        }
        return null;
    }

    public String getFileTime(long filetime) {
        String ftime = formatter.format(new Date(filetime));
        return ftime;
    }

    public String getFileSize(long filesize) {
        DecimalFormat df = new DecimalFormat("#.00");
        StringBuffer mstrbuf = new StringBuffer();

        if (filesize < 1024) {
            mstrbuf.append(filesize);
            mstrbuf.append(" B");
        } else if (filesize < 1048576) {
            mstrbuf.append(df.format((double) filesize / 1024));
            mstrbuf.append(" K");
        } else if (filesize < 1073741824) {
            mstrbuf.append(df.format((double) filesize / 1048576));
            mstrbuf.append(" M");
        } else {
            mstrbuf.append(df.format((double) filesize / 1073741824));
            mstrbuf.append(" G");
        }

        df = null;

        return mstrbuf.toString();
    }

    static class ListHolder {
        ImageView mfileIcon;
        TextView mfileName;
        TextView mfileSize;
        TextView mfileTime;
        CheckBox mChkBox;
    }
    
    public static class PFile implements PYRender{
        public File file;
        public String pyName;
        
        public PFile(File f) {
            file = f;
        }

        @Override
        public String getPYName() {
            if(pyName == null) {
                pyName = PinyinUtil.stringArrayToString(PinyinUtil.getHeadByString( file.getName().toLowerCase()));
            }
            return pyName;
        }
    }
}